package com.yintong.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lyb.R;
import com.lyb.app.App;
import com.lyb.base.BaseActivity;
import com.lyb.dialog.AlertFragmentDialog;
import com.lyb.events.RefreshMineEvent;
import com.lyb.util.ToastUtil;
import com.lyb.util.Tool;
import com.yintong.bean.GetUserInfoBean;
import com.yintong.contract.BindBankContract;
import com.yintong.pay.utils.BaseHelper;
import com.yintong.pay.utils.Constants;
import com.yintong.pay.utils.MobileSecurePayer;
import com.yintong.presenter.BindBankPresenter;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import butterknife.BindView;

public class BindBankActivity extends BaseActivity<BindBankPresenter> implements BindBankContract.View {

    @BindView(R.id.jump_btn)
    public TextView jump_btn;

    @BindView(R.id.name)
    public TextView mName;

    @BindView(R.id.bankno)
    public EditText mBankNo;

    @BindView(R.id.tv_back)
    public TextView mTvBack;

    public static void goBindBank(Context context) {
        Intent intent = new Intent(context, BindBankActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.layout_bind_bank;
    }

    @Override
    public void initPresenter() {
        mPresenter.init(this);
    }

    @Override
    public void loadData() {
        mTvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mPresenter.getUserInfo();
    }

    private Handler mHandler = createHandler();

    private Handler createHandler() {
        return new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                if (TextUtils.isEmpty(strRet)) {
                    ToastUtil.show("操作失败，请重试");
                    return;
                }
                switch (msg.what) {
                    case Constants.RQF_PAY: {
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        String retCode = objContent.optString("ret_code");
                        String retMsg = objContent.optString("ret_msg");

                        if (retMsg.contains("卡bin信息不存在")||retMsg.contains("银行卡卡号 card_no")) {
                            retMsg = "银行卡号输入错误，请重新输入";
                        }
                        // 成功
                        if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
//                            ResultChecker checker = new ResultChecker(strRet);
//                            checker.checkSign();
//                            BaseHelper.showDialog(BindBankActivity.this, "提示",
//                                    "签约成功，交易状态码：" + retCode + " 返回报文:" + strRet,
//                                    android.R.drawable.ic_dialog_alert);
                            mPresenter.uploadBindResult(mBankNo.getEditableText().toString().trim(), strRet);
                            break;
                        } else if (Constants.RET_CODE_PROCESS.equals(retCode)) {
                            // TODO 处理中，掉单的情形
                            String resulPay = objContent.optString("result_pay");
                            if (Constants.RESULT_PAY_PROCESSING
                                    .equalsIgnoreCase(resulPay)) {
//                                BaseHelper.showDialog(BindBankActivity.this, "提示",
//                                        objContent.optString("ret_msg") + "交易状态码："
//                                                + retCode + " 返回报文:" + strRet,
//                                        android.R.drawable.ic_dialog_alert);L
                                String stateContent = objContent.optString("ret_msg") + "\n交易状态码："
                                        + retCode + "\n返回报文:" + strRet;
                                new AlertFragmentDialog.Builder(BindBankActivity.this).setTitle("提示").setContent(retMsg).setRightBtnText("确定").build();
                                mPresenter.uploadBindState(stateContent);
                            }
                        } else {
                            // TODO 失败
//                            BaseHelper.showDialog(BindBankActivity.this, "提示", retMsg
//                                            + "，交易状态码:" + retCode + " 返回报文:" + strRet,
//                                    android.R.drawable.ic_dialog_alert);
                            String stateContent = retMsg + "\n交易状态码："
                                    + retCode+ "\n返回报文:" + strRet;
                            new AlertFragmentDialog.Builder(BindBankActivity.this).setTitle("提示").setContent(retMsg).setRightBtnText("确定").build();
                            mPresenter.uploadBindState(stateContent);
                        }
                    }
                    break;
                    default:
                        break;
                }
                super.handleMessage(msg);
            }
        };

    }

    @Override
    public void showLoading(String content) {
        App.loadingContent(mActivity, content);
    }

    @Override
    public void stopLoading() {
        App.hideLoading();
    }

    @Override
    public void showErrorMsg(String msg,String type) {
        if (TextUtils.equals("dialog", type)) {
            EventBus.getDefault().post(new RefreshMineEvent());
            new AlertFragmentDialog.Builder(BindBankActivity.this).setTitle("绑卡成功").setContent("请前往首页进行借款~").setRightBtnText("确定").setCancel(false).setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                @Override
                public void dialogRightBtnClick() {
                    finish();
                }
            }).build();
        } else if (TextUtils.equals("-1",type)){
            Toast.makeText(mContext, "绑卡失败，请输入正确信息后重新绑卡", Toast.LENGTH_SHORT).show();
        }else {
            ToastUtil.showToast(msg);
            if (TextUtils.equals("finish", type)) {
                finish();
            }
        }
    }

    @Override
    public boolean sign(String content4Pay) {
        MobileSecurePayer msp = new MobileSecurePayer();
        boolean bRet = msp.payRepaySign(content4Pay, mHandler,
                Constants.RQF_PAY, BindBankActivity.this, false);
        return bRet;
    }

    @Override
    public void getUserInfoSuccess(final GetUserInfoBean bean) {
        //数据完整性检测
        if(TextUtils.isEmpty(bean.getUserName()) /*|| TextUtils.isEmpty(bean.getCardNo())*/){
            ToastUtil.show("登录信息失效，请稍后登录再试");
            finish();
            return;
        }

        if (App.getConfig().getUserInfo() != null) {
            mName.setText(bean.getUserName());
        }

        if (bean.getCardNo()!=null){
            mBankNo.setText(bean.getCardNo());
            jump_btn.setText("更换银行卡");
        }else {
            jump_btn.setText("绑定银行卡");
        }
        jump_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Tool.isFastDoubleClick()) {
                    return;
                }

                if(TextUtils.isEmpty(mBankNo.getEditableText().toString())){
                    ToastUtil.show("请填写银行卡信息");
                }else {
                    mPresenter.bindCard(mBankNo.getEditableText().toString().trim(),bean);
                }
            }
        });
    }
}

